from collections import OrderedDict

from django.db.models import Count
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response


# 路由访问方式，page第一页，page_size每页显示数量
from db.models import XlzTopic, XlzNews


class TopicListPager(PageNumberPagination):
    page_size_query_param = 'page_size'  # 前端请求的第几页参数字段
    topic_queryset = XlzTopic.objects.values('content').annotate(Count('news_id')).order_by('-news_id__count')[0:6]
    # 用户动态查询
    queryset = XlzNews.objects.all()
    if topic_queryset and queryset:
        hot_topics = []
        for topic in topic_queryset:
            hot_topics.append(topic['content'])

    # 自定义分页形式
    def get_paginated_response(self, data):
        # OrderedDict字典的子类，生成有序的字典
        return Response(OrderedDict([
            ('hot_topics',self.hot_topics),
            ('count', self.page.paginator.count),
            ('page_range', list(self.page.paginator.page_range)),  # 页码范围
            ('has_next', self.page.has_next()),
            ('has_last', self.page.has_previous()),
            ('results', data)
        ]))
